<?php

/*
* Copyright (C) 2015 xiuno.com
*/

// 安全缩略，按照ID存储
/*
	$arr = image_safe_thumb('abc.jpg', 123, '.jpg', './upload/', 100, 100);
	array(
		'filesize'=>1234,
		'width'=>100,
		'height'=>100,
		'fileurl' => '001/0123/1233.jpg'
	);
*/

// 不包含 .
function image_ext($filename) {
	return strtolower(substr(strrchr($filename, '.'), 1));
}

// 获取安全的文件名，如果文件存在，则加时间戳和随机数，避免重复
function image_safe_name($filename, $dir) {
	$time = $_SERVER['time'];
	// 最后一个 . 保留，其他的 . 替换
	$s1 = substr($filename, 0, strrpos($filename, '.'));
	$s2 = substr(strrchr($filename, '.'), 1);
	$s1 = preg_replace('#\W#', '_', $s1);
	$s2 = preg_replace('#\W#', '_', $s2);
	if(is_file($dir."$s1.$s2")) {
		$newname = $s1.$time.rand(1, 1000).'.'.$s2;
	} else {
		$newname = "$s1.$s2";
	}
	return $newname;
}

// 缩略图的名字
function image_thumb_name($filename) {
	return substr($filename, 0, strrpos($filename, '.')).'_thumb'.strrchr($filename, '.');
}

// 随即文件名
function image_rand_name($k) {
	$time = $_SERVER['time'];
	return $time.'_'.rand(1000000000, 9999999999).'_'.$k;
}

/*
	实例：
	image_set_dir(123, './upload');

	000/000/1.jpg
	000/000/100.jpg
	000/000/100.jpg
	000/000/999.jpg
	000/001/1000.jpg
	000/001/001.jpg
	000/002/001.jpg
*/
function image_set_dir($id, $dir) {

	$id = sprintf("%09d", $id);
	$s1 = substr($id, 0, 3);
	$s2 = substr($id, 3, 3);
	$dir = $dir."$s1/$s2";
	!is_dir($dir) && mkdir($dir, 0777, TRUE);

	return "$s1/$s2";
}

// 取得 user home 路径
function image_get_dir($id) {
	$id = sprintf("%09d", $id);
	$s1 = substr($id, 0, 3);
	$s2 = substr($id, 3, 3);
	return "$s1/$s2";
}

/*
	实例：
 	image_thumb('xxx.jpg', 'xxx_thumb.jpg', 200, 200);

 	返回：
 	array('filesize'=>0, 'width'=>0, 'height'=>0)
 */
function image_thumb($sourcefile, $destfile, $forcedwidth = 80, $forcedheight = 80) {
	$return = array('filesize'=>0, 'width'=>0, 'height'=>0);
	$destext = image_ext($destfile);
	if(!in_array($destext, array('gif', 'jpg', 'bmp', 'png'))) {
		return $return;
	}

	$imginfo = get_imagesize($sourcefile);//低版本的getimagesize()有安全漏洞
	$src_width = $imginfo[0];
	$src_height = $imginfo[1];
	if($src_width == 0 || $src_height == 0) {
		return $return;
	}

	if(!function_exists('imagecreatefromjpeg')) {
		copy($sourcefile, $destfile);
		$return = array('filesize'=>filesize($destfile), 'width'=>$src_width, 'height'=>$src_height);
		return $return;
	}

	// 按规定比例缩略
	$src_scale = $src_width / $src_height;
	$des_scale = $forcedwidth / $forcedheight;
	if($src_width <= $forcedwidth && $src_height <= $forcedheight) {
		$des_width = $src_width;
		$des_height = $src_height;
	} elseif($src_scale >= $des_scale) {
		$des_width = ($src_width >= $forcedwidth) ? $forcedwidth : $src_width;
		$des_height = $des_width / $src_scale;
		$des_height = ($des_height >= $forcedheight) ? $forcedheight : $des_height;
	} else {
		$des_height = ($src_height >= $forcedheight) ? $forcedheight : $src_height;
		$des_width = $des_height * $src_scale;
		$des_width = ($des_width >= $forcedwidth) ? $forcedwidth : $des_width;
	}

	switch ($imginfo['mime']) {
		case 'image/jpeg':
			$img_src = imagecreatefromjpeg($sourcefile);
			!$img_src && $img_src = imagecreatefromgif($sourcefile);
			break;
		case 'image/gif':
			$img_src = imagecreatefromgif($sourcefile);
			!$img_src && $img_src = imagecreatefromjpeg($sourcefile);
			break;
		case 'image/png':
			$img_src = imagecreatefrompng($sourcefile);
			break;
		case 'image/wbmp':
			$img_src = imagecreatefromwbmp($sourcefile);
			break;
		default :
			return $return;
	}

	if(!$img_src) return $return;

	$img_dst = imagecreatetruecolor($des_width, $des_height);
	imagefill($img_dst, 0, 0 , 0xFFFFFF);
	imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $des_width, $des_height, $src_width, $src_height);

	$conf = _SERVER('conf');
	$tmppath = isset($conf['tmp_path']) ? $conf['tmp_path'] : ini_get('upload_tmp_dir').'/';
	$tmppath == '/' AND $tmppath = './tmp/';

	$tmpfile = $tmppath.md5($destfile).'.tmp';
	switch($destext) {
		case 'jpg': imagejpeg($img_dst, $tmpfile, 90); break;
		case 'gif': imagegif($img_dst, $tmpfile); break;
		case 'png': imagepng($img_dst, $tmpfile); break;
	}
	$r = array('filesize'=>filesize($tmpfile), 'width'=>$des_width, 'height'=>$des_height);;
	copy($tmpfile, $destfile);
	is_file($tmpfile) && unlink($tmpfile);
	imagedestroy($img_dst);
	return $r;
}


/**
 * 图片裁切
 *
 * @param string $sourcefile	原图片路径(绝对路径/abc.jpg)
 * @param string $destfile 		裁切后生成新名称(绝对路径/rename.jpg)
 * @param int $clipx 			被裁切图片的X坐标
 * @param int $clipy 			被裁切图片的Y坐标
 * @param int $clipwidth 		被裁区域的宽度
 * @param int $clipheight 		被裁区域的高度
 * image_clip('xxx/x.jpg', 'xxx/newx.jpg', 10, 40, 150, 150)
 */
function image_clip($sourcefile, $destfile, $clipx, $clipy, $clipwidth, $clipheight) {
	$getimgsize = get_imagesize($sourcefile);//低版本的getimagesize()有安全漏洞
	if(empty($getimgsize) || intval($getimgsize[0] ?? 0) * intval($getimgsize[1] ?? 0) == 0 ) {
		return 0;
	} else {
		$imgwidth = $getimgsize[0];
		$imgheight = $getimgsize[1];
		if($imgwidth == 0 || $imgheight == 0) {
			return 0;
		}
	}

	if(!function_exists('imagecreatefromjpeg')) {
		copy($sourcefile, $destfile);
		return filesize($destfile);
	}
	switch($getimgsize[2]) {
		case 1 :
			$imgcolor = imagecreatefromgif($sourcefile);
			break;
		case 2 :
			$imgcolor = imagecreatefromjpeg($sourcefile);
			break;
		case 3 :
			$imgcolor = imagecreatefrompng($sourcefile);
			break;
	}

	if(!$imgcolor) return 0;

	$img_dst = imagecreatetruecolor($clipwidth, $clipheight);
	imagefill($img_dst, 0, 0 , 0xFFFFFF);
	imagecopyresampled($img_dst, $imgcolor, 0, 0, $clipx, $clipy, $imgwidth, $imgheight, $imgwidth, $imgheight);

	$conf = _SERVER('conf');
	$tmppath = isset($conf['tmp_path']) ? $conf['tmp_path'] : ini_get('upload_tmp_dir').'/';
	$tmppath == '/' AND $tmppath = './tmp/';

	$tmpfile = $tmppath.md5($destfile).'.tmp';
	imagejpeg($img_dst, $tmpfile, 100);
	$n = filesize($tmpfile);
	copy($tmpfile, $destfile);
	is_file($tmpfile) && @unlink($tmpfile);
	return $n;
}

// 先裁切后缩略，因为确定了，width, height, 不需要返回宽高。
function image_clip_thumb($sourcefile, $destfile, $forcedwidth = 80, $forcedheight = 80) {
	// 获取原图片宽高
	$getimgsize = get_imagesize($sourcefile);//低版本的getimagesize()有安全漏洞
	if(empty($getimgsize) || intval($getimgsize[0] ?? 0) * intval($getimgsize[1] ?? 0) == 0) {
		return 0;
	} else {
		$src_width = $getimgsize[0];
		$src_height = $getimgsize[1];
		if($src_width == 0 || $src_height == 0) {
			return 0;
		}
	}

	$src_scale = $src_width / $src_height;
	$des_scale = $forcedwidth / $forcedheight;

	if($src_width <= $forcedwidth && $src_height <= $forcedheight) {
		$des_width = $src_width;
		$des_height = $src_height;
		$n = image_clip($sourcefile, $destfile, 0, 0, $des_width, $des_height);
		return filesize($destfile);
	// 原图为横着的矩形
	} elseif($src_scale >= $des_scale) {
		// 以原图的高度作为标准，进行缩略
		$des_height = $src_height;
		$des_width = $src_height / $des_scale;
		$n = image_clip($sourcefile, $destfile, 0, 0, $des_width, $des_height);
		if($n <= 0) return 0;
		$r = image_thumb($destfile, $destfile, $forcedwidth, $forcedheight);
		return $r['filesize'];
	// 原图为竖着的矩形
	} else {
		// 以原图的宽度作为标准，进行缩略
		$des_width = $src_width;
		$des_height = $src_width / $des_scale;

		// echo "src_scale: $src_scale, src_width: $src_width, src_height: $src_height \n";
		// echo "des_scale: $des_scale, forcedwidth: $forcedwidth, forcedheight: $forcedheight \n";
		// echo "des_width: $des_width, des_height: $des_height \n";
		// exit;

		$n = image_clip($sourcefile, $destfile, 0, 0, $des_width, $des_height);
		if($n <= 0) return 0;
		$r = image_thumb($destfile, $destfile, $forcedwidth, $forcedheight);
		return $r['filesize'];
	}
}

function image_safe_thumb($sourcefile, $id, $ext, $dir1, $forcedwidth, $forcedheight, $randomname = 0) {
	$time = $_SERVER['time'];
	$ip = $_SERVER['ip'];
	$dir2 = image_set_dir($id, $dir1);
	$filename = $randomname ? md5(rand(0, 1000000000).$time.$ip).$ext : $id.$ext;
	$filepath = "$dir1$dir2/$filename";
	$arr = image_thumb($sourcefile, $filepath, $forcedwidth, $forcedheight);
	$arr['fileurl'] = "$dir2/$filename";
	return $arr;
}

// image_thumb('D:/image/IMG_0433.JPG', 'd:/image/xxx.gif');
// echo image_clip_thumb('d:/image/editor_bg.gif', 'd:/image/editor_bg_2.gif', 200, 200);






/**
 * 图片扩展名值转换为图片类型
 * @param string $imgType 要转换的IMAGETYPE_XXX
 * @return int IMAGETYPE_*
 *
 */
function extension_to_image_type(string $extension):int
{
    static $imgTypesKV = [
        'bmp' => IMAGETYPE_BMP,
        'gif' => IMAGETYPE_GIF,
        'ico' => IMAGETYPE_ICO,
        'iff' => IMAGETYPE_IFF,
        'jb2' => IMAGETYPE_JB2,
        'jp2' => IMAGETYPE_JP2,
        'jpc' => IMAGETYPE_JPC,
        'jpeg'=> IMAGETYPE_JPEG2000,
        'jpg' => IMAGETYPE_JPEG,
        'jpx' => IMAGETYPE_JPX,
        'png' => IMAGETYPE_PNG,
        'psd' => IMAGETYPE_PSD,
        'swc' => IMAGETYPE_SWC,
        'swf' => IMAGETYPE_SWF,
        'tiff'=> IMAGETYPE_TIFF_II,
        'wbmp'=> IMAGETYPE_WBMP,
        'xbm' => IMAGETYPE_XBM
    ];

    if (empty($extension)) return IMAGETYPE_UNKNOWN;
    $extension = trim($extension, " \t\n\r\0\x0B*.?");
    if (isset($imgTypesKV[$extension])) return $imgTypesKV[$extension];
    return IMAGETYPE_UNKNOWN;
}
/**
 * Get Mime by Extension
 *
 * 根据 static/mimes.php 文件中的配置将文件扩展名转换为 MIME 类型。 如果无法判断 MIME 类型或 MIME 配置文件读取失败，则返回 FALSE 。
 *
 * Note: 这个函数只是一种简便的判断 MIME 类型的方法，并不准确，所以 请不要用于安全相关的地方。
 *
 * @param string $filename File name
 * @return    string
 */
function get_mime_by_extension($filename)
{
    $mimes = &Mimes::$mimes;

    if (empty($mimes)) {
        return FALSE;
    }

    $extension = strtolower(substr(strrchr($filename, '.'), 1));

    if (isset($mimes[$extension])) {
        return is_array($mimes[$extension])
            ? current($mimes[$extension]) // Multiple mime types, just give the first one
            : $mimes[$extension];
    }

    return FALSE;
}
function mime_type_to_image_type($mimeType)
{
    static $mimeTypes = [
        'image/gif' => IMAGETYPE_GIF,
        'image/jpeg' => IMAGETYPE_JPEG,
        'image/png' => IMAGETYPE_PNG,
        'application/x-shockwave-flash' => IMAGETYPE_SWF,
        'image/psd' => IMAGETYPE_PSD,
        'image/bmp' => IMAGETYPE_BMP,
        'image/tiff' => IMAGETYPE_TIFF_II,
        'image/jp2' => IMAGETYPE_JP2,
        'image/iff' => IMAGETYPE_IFF,
        'image/vnd.wap.wbmp' => IMAGETYPE_WBMP,
        'image/xbm' => IMAGETYPE_XBM,
        'image/vnd.microsoft.icon' => IMAGETYPE_ICO,
    ];
    if (isset($mimeTypes[$mimeType])) return $mimeTypes[$mimeType];
    return IMAGETYPE_UNKNOWN;
}

/**
 * 获取图片文件类型
 * @param string $fileData 文件名或者数据
 * @param bool $is_img_data true为图片的数据,false为文件路径（默认）
 * @return false|int
 */
function get_img_type($fileData,$is_img_data=false)
{
    if (!$is_img_data && !is_file($fileData)) return false;
    $fileTypi = IMAGETYPE_UNKNOWN;
    if (!$is_img_data && function_exists('exif_imagetype'))
        $fileTypi = @exif_imagetype($fileData);
    else {
        if (!$is_img_data && function_exists('finfo_open')) {//已经开启php_fileinfo.dll扩展：
            $handle = finfo_open(FILEINFO_MIME_TYPE);
            $fileType = finfo_file($handle, $fileData);// Return information about a file
            finfo_close($handle);
        } else {
            //若没有启用扩展 fileinfo 采用此方式获取类型：
            $bin = null;
            if (!$is_img_data){
                $file = fopen($fileData, 'rb');
                $bin = fread($file, 2); //只读2字节
                fclose($file);
            }
            else
                $bin = &$fileData;
            $strInfo = @unpack('C2chars', $bin);
            $typeCode = intval($strInfo['chars1'] . $strInfo['chars2']);
            $fileType = "application/octet-stream";
            switch ($typeCode) {
                case 1:// ICO files start with a 2-byte header: 0x00 0x01 or 0x00 0x02
                case 2:// This is not a complete check, but it can serve as a basic identification
                    $fileType = 'image/x-icon';
                    break;
                case 255216:
                    $fileType = 'image/jpeg';
                    break;
                case 255:
                    if (substr($bin, 4, 4) == "\x6A\x50\x20\x20") {
                        $fileType = 'image/jpeg';
                    }
                    break;
                case 7173:
                    $fileType = 'image/gif';
                    break;
                case 13780:
                    $fileType = 'image/png';
                    break;
                case 6677:
                    $fileType = 'image/wbmp';
                    break;
                case 7777:
                    $fileType = 'image/tiff';
                    break;
                case 6667:// BMP does not have a unique magic number, it starts with "BM"
                    $fileType = 'image/bmp';
                    break;
                default:
                    if(substr($bin, 0, 7) == "#define")// XBM files start with the magic string "#define"
                        $fileType = 'image/xbm';
                    break;
            }
            // 修复某些图片类型的签名识别
            if ($strInfo['chars1'] == '-1' && $strInfo['chars2'] == '-40') {
                $fileType = 'image/jpeg';
            }
            if ($strInfo['chars1'] == '-119' && $strInfo['chars2'] == '80') {
                $fileType = 'image/png';
            }
        }
        $fileTypi = mime_type_to_image_type($fileType);
    }
    return $fileTypi;
}

/**
 * 获取指定图片文件的图像资源句柄
 * @param String $imgpath 图片文件的路径,不会检查文件是否存在
 * @param int $imgtype ,默认为IMAGETYPE_JPEG
 * return resource|false
 */
function get_img_resource(String $imgpath, $imgtype = IMAGETYPE_JPEG)
{
    if (empty($imgpath) || $imgtype == IMAGETYPE_UNKNOWN) return false;
    $src_image = false;
    if(!is_file($imgpath) && strlen($imgpath) > 256) $src_image = imagecreatefromstring($imgpath);
    elseif ($imgtype == IMAGETYPE_JPEG || $imgtype == IMAGETYPE_JPEG2000) $src_image = imagecreatefromjpeg($imgpath);
    elseif ($imgtype == IMAGETYPE_GIF) $src_image = imagecreatefromgif($imgpath);
    elseif ($imgtype == IMAGETYPE_PNG) $src_image = imagecreatefrompng($imgpath);
    elseif ($imgtype == IMAGETYPE_WBMP) $src_image = imagecreatefromwbmp($imgpath);
    elseif ($imgtype == IMAGETYPE_WEBP) $src_image = imagecreatefromwebp($imgpath);
    elseif ($imgtype == IMAGETYPE_XBM) $src_image = imagecreatefromxbm($imgpath);
    elseif ($imgtype == IMG_XPM) $src_image = imagecreatefromxpm($imgpath);
    return $src_image;
}

/**
 * 以指定图片格式保存图片文件流;警告:有可能改变$savepath,如果成功会关闭文件流,失败则直接返回
 * @param resource $img_res 图片文件流
 * @param String $savepath 保存路径
 * @param int $imgtype IMAGETYPE_XXX
 * @param int $quality 保存质量
 * @param bool $closeres 是否关闭文件流,默认为true
 * @param int $Arg_color 其它颜色参数,格式为IMAGETYPE_WBMP时,为前景颜色
 * @return bool|String 返回false表示错误,或者返回保存后的路径
 */
function save_img_resource($img_res, String $savepath, $imgtype = IMAGETYPE_JPEG, $quality = 75, $closeres = true, $Arg_color = 0)
{
    if (empty($img_res) || empty($savepath) || !is_resource($img_res))
        return false;
    $retv = false;
    //取保存路径判断是否存在:
    $savedir = dirname($savepath);
    if (!file_exists($savedir)) xn_mkdir($savedir, true);
    $curExt = strtolower(substr(basename($savepath), -4));
    if ($curExt == '.php' || $curExt == '.jsp' || $curExt == '.htm' || $curExt == 'html' || ($curExt != 'jpeg' && $curExt[0] != '.' && $curExt != 'webp'))
        $savepath = $savepath . image_type_to_extension($imgtype);
    switch ($imgtype) {
        case IMAGETYPE_PNG:
            if ($quality > 9) $quality = $quality / 100.00 * 9;
            $retv = imagepng($img_res, $savepath, $quality);
            break;
        case IMAGETYPE_GIF:
            $retv = imagegif($img_res, $savepath);
            break;
        case IMAGETYPE_WEBP:
            $retv = imagewebp($img_res, $savepath, $quality);
            break;
        case IMAGETYPE_WBMP:
            $retv = imagewbmp($img_res, $savepath, $Arg_color);
            break;
        default:
            $retv = ImageJpeg($img_res, $savepath, $quality);
            break;
    }
    if ($closeres && is_resource($img_res))
        imagedestroy($img_res);
    if ($retv)
        return $savepath;
    return $retv;
}


/**
 * 获取图片信息: getimagesi2e的安全版本,需要GD库的支持,检查图片内的PHP标签
 * @param mixed $fileData
 * @param int $data_type 数据类型：0-文件(默认),1-图片数据，2-resource，文件流，3-图片句柄（未实现），
 * @param array|null $imageinfo
 * @return array
 */
function &get_imagesize($rc_hander,int $data_type=0, array &$imageinfo = null):array
{
    $ret = [0,0,'','width="0" height="0"','mime'=>''];
    if (empty($rc_hander)) return $ret;
    $str = '';
    $fp = null;
    //检查要操作的图片文件是否包含PHP代码:
    switch ($data_type){
        case 0:
            if(!is_file($rc_hander)) return $ret;
            if(is_php(5.6)){//5.3.1已经修复getimagesize的BUG
                $r = getimagesize($rc_hander, $imageinfo);
                if(!$r) $r = $ret;
                return $r;
            }
            $fp = fopen($rc_hander, 'r');
            break;
        case 1:
            $str = &$rc_hander;
            break;
        case 2:
            if(ftell($rc_hander) < 1) return $ret;//文件长度为空
            $fp = $rc_hander;
            break;
        case 3:
            //if(!is_resource($rc_hander)) return $ret;
            return $ret;
            break;
        default:
            break;
    }
    if(!$fp && is_resource($fp)){
        $str = '';
        $buffer = 4096; //每次读取 4096 字节
        while (!feof($fp)) {//循环读取，直至读取完整个文件
            $str .= fread($fp, $buffer);
        }
        fclose($fp);
    }
    //图片中的脚本检测:
    if(empty($str) || preg_match('/(<\?php\b|\beval\s*\(|<script\b)|<\?.+\?>|<%.+%>/is',$str) > 0){//嵌入了危险代码
        return $ret;
    }
    if ($data_type == 0 && (isset($imageinfo) || !function_exists('imagesx'))) {
        $ret = getimagesize($rc_hander, $imageinfo);
    }
    else {
        $checkext = get_img_type($rc_hander,$data_type > 0);
        if ($checkext == IMAGETYPE_UNKNOWN) return $ret;
        if ($data_type == 0)
            $src_image = get_img_resource($rc_hander, $checkext);
        elseif (!empty($str))
            $src_image = imagecreatefromstring($str);
        unset($str);
        if ($src_image) {
            $ret = array();
            $ret[] = ImageSX($src_image); //获得图片宽
            $ret[] = ImageSY($src_image); //获得图片高
            $ret[] = $checkext;
            $ret[] = 'width="' . strval($ret[0]) . '" height="' . strval($ret[1]) . '"'; //内容为“height="yyy" width="xxx"”
            $ret['mime'] = image_type_to_mime_type($checkext);
            imagedestroy($src_image);
        }
    }
    return $ret;
}

/**
 * 远程获取图片
 *
 * @param array $imgurls 用于抓取图片的网页地址数组,引用传递
 * @param array $savepaths 保存图片的地址数组,引用传递,为空则由filepath和一个随机文件名组合成新的文件名
 * @param String $filepath 保存图片的缺省路径
 * @param int minsize 抓取图片的最小文件大小,默认为4K
 * @param int max_execution_even 每次远程请求的最大等待时长,默认为6秒
 * @return int -2:网页地址数组参数错误,-1:指定的保存路径错误,n:成功个数
 */
function capture_remote_imgs(array &$imgurls, array &$savepaths, $filepath = '', $minsize = 4096, $max_execution_even = 6)
{
    if (empty($imgurls) || count($imgurls) < 1)
        return -2;
    if (empty($filepath) || count($savepaths) < 1)
        return -1;
    $get_img_count = 0;
    $succ_img_count = 0;
    $oldexetime = -1;
    $fpendpos = strlen($filepath) - 1;
    if ($fpendpos >= 0 && $filepath[$fpendpos] != '/' && $filepath[$fpendpos] != '\\') {
        $filepath = $filepath . '/';
    }
    foreach ($imgurls as $img_url) {
        $succR = false;
        if (preg_match('#^https?://.+#i', $img_url)) {
            if ($oldexetime == -1) {
                $oldexetime = ini_get('max_execution_time');
                set_time_limit($max_execution_even * count($imgurls));//设置脚本的最大执行时间,根据参数设置
            }
            //将图片内容读入一个字符串
            $img_data = @file_get_contents($img_url);   //屏蔽掉因为图片地址无法读取导致的warning错误
            if (strlen($img_data) > $minsize) //下载size比限制大的图片
            {
                if (empty($savepaths[$get_img_count])) {
                    $imgexta = array();
                    $imgext = '.jpg';
                    if (preg_match('/.+?\.(jpe?g|png|gif|bmp|svg|webp|tiff?|wmf)([?#].+)?$/i', $img_url, $imgexta)) {
                        $imgext = $imgexta[1];
                    }
                    $savepaths[$get_img_count] = $filepath . xn_rand(10) . $imgext;//随机文件名
                } else {
                    if (strpos($savepaths[$get_img_count], '/') === FALSE && strpos($savepaths[$get_img_count], '\\') === FALSE) {
                        $savepaths[$get_img_count] = $filepath . $savepaths[$get_img_count];//只有文件名的要添加路径
                    }
                }
                $saveToPath = dirname($savepaths[$get_img_count]);
                if (!is_dir($saveToPath)) xn_mkdir($saveToPath, null, true);
                if('/'==DIRECTORY_SEPARATOR) $savepaths[$get_img_count] = str_replace('\\','/',$savepaths[$get_img_count]);
                else $savepaths[$get_img_count] = str_replace('/','\\',$savepaths[$get_img_count]);
                $img_size = file_put_contents($savepaths[$get_img_count], $img_data);
                if ($img_size) {
                    $succR = true;
                    $succ_img_count++;
                }
            }
        }
        if ($succR == false) {
            $savepaths[$get_img_count] = '';
        }
        $get_img_count++;
    }
    if ($oldexetime > -1) {
        set_time_limit($oldexetime);//恢复最大执行时间
    }
    return $succ_img_count;
}

/**
 * 根据HTML DOM得到的IMG元素属性SRC获取图片并检查是否符合要求
 * @param string $imgsrc
 * @param array $TitleImageCfg TitleImage配置
 * @param string $savetitleimgpathRoot 保存图片的根路径(会在后面加上titleimg/remote),如果$tid没有指定,则此为完整文件名
 * @param int $tid 主题ID,用于titleimgpath的构建
 * @param int $imgheight_min 最小高度限制,0为不限
 * @param int $imgwidth_min 最小宽度限制,0为不限
 * @param string $basehref 图片地址$imgsrc的主机基址
 * @return array|false 如果是返回数组则包含(imgfile ,width,height),可选的(istmp)
 */
function GetImgFromDomSrc(string $imgsrc, array $TitleImageCfg, string $savetitleimgpathRoot, $tid, $imgheight_min, $imgwidth_min, $basehref = null)
{
    $ret = array();
    $my_host = $_SERVER['HTTP_HOST'];
    if (stripos($my_host, 'www.') === 0)
        $my_host = substr($my_host, 4);
    if (!empty($basehref) && $basehref != $my_host && $basehref != $_SERVER['HTTP_HOST']) {
        if (strpos($basehref, '://') == false) {
            $basehref = 'http://' . $basehref;
        }
        $imgsrc = $basehref . $imgsrc;
    }
    //判断是否为本地图片
    if (stripos($imgsrc, 'http://') === 0 || stripos($imgsrc, 'https://') === 0) {
        $urlmatch2 = array();
        if (preg_match('#^https?://(www\.)?' . preg_quote($my_host) . '(/.+)$#i', $imgsrc, $urlmatch2) == 0) //为远程图片
        {
            $pathlastchr = $savetitleimgpathRoot[strlen($savetitleimgpathRoot) - 1];
            $has_dir_sep = ($pathlastchr == '/' || $pathlastchr == '\\');
            if ($tid == 0) {
                if (!$has_dir_sep) {
                    $tid = xn_rand(8);
                } else {
                    $tid = basename($savetitleimgpathRoot);//取文件名
                    $savetitleimgpathRoot = dirname($savetitleimgpathRoot) . '/';
                }
            } else
                $tid = strval($tid);
            if (strpos($tid, '.') < 1)
                $tid = $tid . '.' . trim($TitleImageCfg['ImageType'], " \t\n\r\0\x0B.*?");
            if (stripos($savetitleimgpathRoot, 'remote') < 1) {
                $savetitleimgpathRoot .= ($has_dir_sep?'':'/') . 'remote/';
            }
            $save_imgs = array($tid);
            $get_imgurls = array($imgsrc);
            $giret = capture_remote_imgs($get_imgurls, $save_imgs, $savetitleimgpathRoot);
            if ($giret > 0)//成功获取远程图片
            {
                $ret['imgfile'] = $save_imgs[0];
                $ret['istmp'] = true;
            }
        } else {
            $teimg1 = $urlmatch2[2];
            if (file_exists($teimg1)) //检测是否存在
            {
                $ret['imgfile'] = $teimg1;
            }
        }
    } else {
        if (file_exists($imgsrc)) {
            $ret['imgfile'] = $imgsrc;
        }
    }
    if (!empty($ret['imgfile'])) {
        $imginfo = get_imagesize($ret['imgfile']);//必须是有效的图片
        if (!empty($imginfo) && $imginfo[0] > 100 && $imginfo[1] > 100 && ($imgheight_min == 0 || $imginfo[1] > $imgheight_min * 1.2) && ($imgwidth_min == 0 || $imginfo[0] > $imgwidth_min * 1.2)) {
            $ret['width'] = $imginfo[0];
            $ret['height'] = $imginfo[1];
        } else {
            @unlink($ret['imgfile']); //立即删除不合规则的图片
        }
    } else $ret = false;
    return $ret;
}

/**
 * 生成缩略图片并保存到指定位置
 * @param String|resource $imgpath 源图片路径
 * @param int $imgheight 缩略图片的高度,0为与$imgwidth等比例缩放
 * @param int $imgwidth 缩略图片的宽度,0为与$imgheight等比例缩放
 * @param String &$savepath 缩略图保存位置,如果没有指定,则根据保存类型自动指定,需要引用传值
 * @param int $imgtype 缩略图类型,默认为IMAGETYPE_JPEG,其它有效值:IMAGETYPE_PNG;IMAGETYPE_GIF;IMAGETYPE_WEBP;IMAGETYPE_WBMP
 * @param bool $delsrc 成功后是否删除源图片
 * @return bool 返回true为成功
 */
function dealthumb($imgpath, $imgheight, $imgwidth, &$savepath, $imgtype = IMAGETYPE_JPEG, $delsrc = false)
{
    if (!file_exists($imgpath)) RelpathToAbspath($imgpath, $imgpath);
    if (!file_exists($imgpath)) return false;
    if ($imgheight + $imgwidth < 10) return false;
    $descdir = dirname($savepath);
    if (!file_exists($descdir)) xn_mkdir($descdir, NULL, true);
    //取得源图片的格式:
    $src_image = null;
    $checkext = get_img_type($imgpath);
    if ($checkext == IMAGETYPE_UNKNOWN) return false;
    $src_image = get_img_resource($imgpath, $checkext);
    $opt_ret = false;
    if ($src_image) {
        $srcW = doubleval(ImageSX($src_image)); //获得图片宽
        $srcH = doubleval(ImageSY($src_image)); //获得图片高
        if ($imgwidth == 0) $imgwidth = intval($imgheight * ($srcW / $srcH));
        if ($imgheight == 0) $imgheight = intval($imgwidth * ($srcH / $srcW));
        if ($srcH <= $imgheight) {
            $opt_ret = $retv = @copy($imgpath, $savepath);
        } else {
            $dst_image = ImageCreateTrueColor($imgwidth, $imgheight);
            $opt_ret = ImageCopyResized($dst_image, $src_image, 0, 0, 0, 0, $imgwidth, $imgheight, $srcW, $srcH);
            if ($opt_ret) {
                $retsavepath = save_img_resource($dst_image, $savepath, $imgtype, 85);
                if ($retsavepath) {
                    $savepath = $retsavepath;
                    $retv = $opt_ret = true;
                } elseif ($dst_image) imagedestroy($dst_image);
            }
        }
        imagedestroy($src_image);
        if ($retv && $delsrc) {
            @unlink($imgpath);
        }
        return $opt_ret;
    }
    return false;
}
/**
 * 求矩形坐标的形状大小,一般根据imagettfbbox和imagettftext返回的结果计算
 * @param array $box 四个角的坐标
 * @return array 如果传入参数无效,返回空数组,数组包含W,H,L,T键
 */
function rect_for_box($box)
{
    $ret = array('W' => 0, 'H' => 0);
    if (empty($box) || !is_array($box) || count($box) < 8)
        return $ret;
    $Xmin = min($box[0], $box[2], $box[4], $box[6]);
    $Xmax = max($box[0], $box[2], $box[4], $box[6]);
    $Ymin = min($box[1], $box[3], $box[5], $box[7]);
    $Ymax = max($box[1], $box[3], $box[5], $box[7]);
    $ret['L'] = $Xmin;
    $ret['T'] = $Ymin;
    $ret['W'] = $Xmax - $Xmin;
    $ret['H'] = $Ymax - $Ymin;
    return $ret;
}


/**
 * 磅PT与PX互相转换
 * @param int $ztype 转换方式,1:PT=>PX,2:PX=>PT
 * @param float $val 要计算的值
 * @param int $Resolution 分辨率,一般为72,其它常见项:96,144
 * @return float|int
 */
function point_pixel(int $ztype, float $val, $Resolution = 72)
{
    //point => pixel
    if ($ztype == 1)//point to pixel
    {
        return $Resolution / 72 * $val;
    } elseif ($ztype == 2) {
        return $val / ($Resolution / 72);
    }
    return $val;
}
/**
 * 将颜色字符串(可以是已命名颜色名称)转换为RGB,可能含有A
 * @param String $colorHex ,如果为空或者random则生成随机颜色
 * @param String $result_format 返回的结果的格式,array/0为包含RGBA的数组,index/1为对应图像的颜色值
 * @param resource $img_res 图像对象,当$result_format为index时使用
 * @return array|bool
 */
function colorname_to_rgb(String $colorHex, $result_format = 'array', $img_res = null)
{
    $ret = array();
    if (($result_format == 'index' || $result_format == 1) && !is_resource($img_res))
        return false;

    if (empty($colorHex) || strtolower($colorHex) == 'random' || $colorHex == '随机') {
        $ret['R'] = mt_rand(0, 255);
        $ret['G'] = mt_rand(0, 255);
        $ret['B'] = mt_rand(0, 255);
        $ret['A'] = mt_rand(0, 127);
    } else {
        $strlens = strlen($colorHex);
        if ($strlens < 3) return false;
        $nameColors = array('aliceblue' => '#F0F8FF',
            'antiquewhite' => '#FAEBD7',
            'aqua' => '#00FFFF',
            'aquamarine' => '#7FFFD4',
            'azure' => '#F0FFFF',
            'beige' => '#F5F5DC',
            'bisque' => '#FFE4C4',
            'black' => '#000000',
            'blanchedalmond' => '#FFEBCD',
            'blue' => '#0000FF',
            'blueviolet' => '#8A2BE2',
            'brown' => '#A52A2A',
            'burlywood' => '#DEB887',
            'cadetblue' => '#5F9EA0',
            'chartreuse' => '#7FFF00',
            'chocolate' => '#D2691E',
            'coral' => '#FF7F50',
            'cornflowerblue' => '#6495ED',
            'cornsilk' => '#FFF8DC',
            'crimson' => '#DC143C',
            'cyan' => '#00FFFF',
            'darkblue' => '#00008B',
            'darkcyan' => '#008B8B',
            'darkgoldenrod' => '#B8860B',
            'darkgray' => '#A9A9A9',
            'darkgreen' => '#006400',
            'darkkhaki' => '#BDB76B',
            'darkmagenta' => '#8B008B',
            'darkolivegreen' => '#556B2F',
            'darkorange' => '#FF8C00',
            'darkorchid' => '#9932CC',
            'darkred' => '#8B0000',
            'darksalmon' => '#E9967A',
            'darkseagreen' => '#8FBC8F',
            'darkslateblue' => '#483D8B',
            'darkslategray' => '#2F4F4F',
            'darkturquoise' => '#00CED1',
            'darkviolet' => '#9400D3',
            'deeppink' => '#FF1493',
            'deepskyblue' => '#00BFFF',
            'dimgray' => '#696969',
            'dodgerblue' => '#1E90FF',
            'firebrick' => '#B22222',
            'floralwhite' => '#FFFAF0',
            'forestgreen' => '#228B22',
            'fuchsia' => '#FF00FF',
            'gainsboro' => '#DCDCDC',
            'ghostwhite' => '#F8F8FF',
            'gold' => '#FFD700',
            'goldenrod' => '#DAA520',
            'gray' => '#808080',
            'green' => '#008000',
            'greenyellow' => '#ADFF2F',
            'honeydew' => '#F0FFF0',
            'hotpink' => '#FF69B4',
            'indianred' => '#CD5C5C',
            'indigo' => '#4B0082',
            'ivory' => '#FFFFF0',
            'khaki' => '#F0E68C',
            'lavender' => '#E6E6FA',
            'lavenderblush' => '#FFF0F5',
            'lawngreen' => '#7CFC00',
            'lemonchiffon' => '#FFFACD',
            'lightblue' => '#ADD8E6',
            'lightcoral' => '#F08080',
            'lightcyan' => '#E0FFFF',
            'lightgoldenrodyellow' => '#FAFAD2',
            'lightgreen' => '#90EE90',
            'lightgrey' => '#D3D3D3',
            'lightpink' => '#FFB6C1',
            'lightsalmon' => '#FFA07A',
            'lightseagreen' => '#20B2AA',
            'lightskyblue' => '#87CEFA',
            'lightslategray' => '#778899',
            'lightsteelblue' => '#B0C4DE',
            'lightyellow' => '#FFFFE0',
            'lime' => '#00FF00',
            'limegreen' => '#32CD32',
            'linen' => '#FAF0E6',
            'magenta' => '#FF00FF',
            'maroon' => '#800000',
            'mediumaquamarine' => '#66CDAA',
            'mediumblue' => '#0000CD',
            'mediumorchid' => '#BA55D3',
            'mediumpurple' => '#9370DB',
            'mediumseagreen' => '#3CB371',
            'mediumslateblue' => '#7B68EE',
            'mediumspringgreen' => '#00FA9A',
            'mediumturquoise' => '#48D1CC',
            'mediumvioletred' => '#C71585',
            'midnightblue' => '#191970',
            'mintcream' => '#F5FFFA',
            'mistyrose' => '#FFE4E1',
            'moccasin' => '#FFE4B5',
            'navajowhite' => '#FFDEAD',
            'navy' => '#000080',
            'oldlace' => '#FDF5E6',
            'olive' => '#808000',
            'olivedrab' => '#6B8E23',
            'orange' => '#FFA500',
            'orangered' => '#FF4500',
            'orchid' => '#DA70D6',
            'palegoldenrod' => '#EEE8AA',
            'palegreen' => '#98FB98',
            'paleturquoise' => '#AFEEEE',
            'palevioletred' => '#DB7093',
            'papayawhip' => '#FFEFD5',
            'peachpuff' => '#FFDAB9',
            'peru' => '#CD853F',
            'pink' => '#FFC0CB',
            'plum' => '#DDA0DD',
            'powderblue' => '#B0E0E6',
            'purple' => '#800080',
            'red' => '#FF0000',
            'rosybrown' => '#BC8F8F',
            'royalblue' => '#4169E1',
            'saddlebrown' => '#8B4513',
            'salmon' => '#FA8072',
            'sandybrown' => '#F4A460',
            'seagreen' => '#2E8B57',
            'seashell' => '#FFF5EE',
            'sienna' => '#A0522D',
            'silver' => '#C0C0C0',
            'skyblue' => '#87CEEB',
            'slateblue' => '#6A5ACD',
            'slategray' => '#708090',
            'snow' => '#FFFAFA',
            'springgreen' => '#00FF7F',
            'steelblue' => '#4682B4',
            'tan' => '#D2B48C',
            'teal' => '#008080',
            'thistle' => '#D8BFD8',
            'tomato' => '#FF6347',
            'turquoise' => '#40E0D0',
            'violet' => '#EE82EE',
            'wheat' => '#F5DEB3',
            'white' => '#FFFFFF',
            'whitesmoke' => '#F5F5F5',
            'yellow' => '#FFFF00',
            'yellowgreen' => '#9ACD32');

        if (isset($nameColors[strtolower($colorHex)])) $colorHex = $nameColors[strtolower($colorHex)];
        if ($colorHex[0] == '#') $colorHex = substr($colorHex, 1);
        elseif ($colorHex[0] == '0' && ($colorHex[1] == 'x' || $colorHex[1] == 'X'))
            $colorHex = substr($colorHex, 2);
        $strlens = strlen($colorHex);
        $ret['A'] = 0;
        if ($strlens == 3) {
            $ret['R'] = hexdec($colorHex[0]);
            $ret['G'] = hexdec($colorHex[1]);
            $ret['B'] = hexdec($colorHex[2]);
        } elseif ($strlens > 5) {
            $ret['R'] = hexdec(substr($colorHex, 0, 2));
            $ret['G'] = hexdec(substr($colorHex, 2, 2));
            $ret['B'] = hexdec(substr($colorHex, 4, 2));
            if ($strlens > 7)
                $ret['A'] = hexdec(substr($colorHex, 6, 2));
        }
    }
    if ($result_format == 'index' || $result_format == 1) {
        if (function_exists('imagecolorallocatealpha'))
            return imagecolorallocatealpha($img_res, $ret['R'], $ret['G'], $ret['B'], $ret['A']);
        return imagecolorallocate($img_res, $ret['R'], $ret['G'], $ret['B']);
    }
    return $ret;
}

/**
 * 由九宫格位置代号获取画布坐标X,Y
 * @param int $poscode 九宫格位置代号,左上1,上中2,右上3,中左4...右下9,0为随机位置
 * @param int $img_width 图片的总宽度
 * @param int $img_height 图片的总高度
 * @param int $slice_width 切片的总宽度
 * @param int $slice_height 切片的总高度(default:20)
 * @param int $slice_left 切片的左边界(default:0)
 * @param int $slice_top 切片的上边界(default:0)
 * @param float $border 边界留空多少?<1为留总宽度的百分之X,否则直接为X px(default:5%)
 * return array|bool:false
 */
function get_draw_position(int $poscode, int $img_width, int $img_height, int $slice_width, int $slice_height = 20, int $slice_left = 0, int $slice_top = 0, $border = 0.05)
{
    if ($img_width == 0 || $img_height == 0 || $slice_width == 0 || $slice_width >= $img_width)
        return false;
    if ($slice_height == 0) $slice_height = 20;
    if ($border < 1)
        $border = intval($img_width * $border);
    $ret = array('X' => $border - $slice_left, 'Y' => $border - $slice_top);
    switch ($poscode) {
        case 0://随机
            $ret['X'] = mt_rand($border - $slice_left, $img_width - $slice_width - $slice_left);
            $ret['Y'] = mt_rand($border - $slice_top, $img_height - $slice_height - $slice_top);
            break;
        case 1:
            break;
        case 2:
            $ret['X'] = ($img_width - $slice_width) / 2 - $slice_left;
            break;
        case 3:
            $ret['X'] = $img_width - $slice_width - $border - $slice_left;
            break;
        case 4:
            $ret['Y'] = ($img_height - $slice_height) / 2 - $slice_top;
            break;
        case 5:
            $ret['Y'] = ($img_height - $slice_height) / 2 - $slice_top;
            $ret['X'] = ($img_width - $slice_width) / 2 - $slice_left;
            break;
        case 6:
            $ret['Y'] = ($img_height - $slice_height) / 2 - $slice_top;
            $ret['X'] = $img_width - $slice_width - $border - $slice_left;
            break;
        case 7:
            $ret['Y'] = $img_height - $slice_height - $border - $slice_top;
            break;
        case 8:
            $ret['Y'] = $img_height - $slice_height - $border - $slice_top;
            $ret['X'] = ($img_width - $slice_width) / 2 - $slice_left;
            break;
        case 9:
            $ret['Y'] = $img_height - $slice_height - $border - $slice_top;
            $ret['X'] = $img_width - $slice_width - $border - $slice_left;
            break;
        default:
            $ret['X'] = $poscode;
            $ret['Y'] = $img_height - $slice_height;
            break;
    }
    return $ret;
}
/**
 * 检测图片对象的边缘,返回数量超过一半的颜色值
 * @param resource $ImgRes
 * @param int $retFormat 返回的数据格式,0为默认的数组包含RGBA属性,1为颜色值,imagecolorat的结果值
 * @return bool|array|int 返回值,false为错误
 */
function ImgEdgeCheckColor($ImgRes, $retFormat = 0)
{
    if (empty($ImgRes) || !is_resource($ImgRes))
        return false;
    $ret = array();
    $w = ImageSX($ImgRes);
    $h = ImageSY($ImgRes);
    $rgb1 = imagecolorat($ImgRes, 0, 0);
    $rgb2 = imagecolorat($ImgRes, $w - 1, 0);
    $rgb3 = imagecolorat($ImgRes, 0, $h - 1);
    $rgb4 = imagecolorat($ImgRes, $w - 1, $h - 1);
    $rgb5 = imagecolorat($ImgRes, $w / 2, 0);
    $rgb6 = imagecolorat($ImgRes, $w / 2, $h - 1);
    $rgb7 = imagecolorat($ImgRes, $w - 1, $h / 2);
    $rgb8 = imagecolorat($ImgRes, 0, $h / 2);
    $xcp = array($rgb1, $rgb2, $rgb3, $rgb4, $rgb5, $rgb6, $rgb7, $rgb8);
    $maxCv = 0;
    $maxCi = $CleanColor = null;
    foreach ($xcp as $ite) {
        if ($maxCi === $ite) continue;
        $xcount = count(array_keys($xcp, $ite, true));
        if ($xcount > $maxCv) {
            $maxCv = $xcount;
            $maxCi = $ite;
        }
    }
    if ($maxCv > 3) $CleanColor = $maxCi;
    if ($CleanColor !== null) {
        if ($retFormat == 0) {
            $ret['R'] = ($CleanColor >> 16) & 0xFF;
            $ret['G'] = ($CleanColor >> 8) & 0xFF;
            $ret['B'] = $CleanColor & 0xFF;
            $ret['A'] = ($CleanColor & 0x7F000000) >> 24;
        } elseif ($retFormat == 1)
            $ret = $CleanColor;
        return $ret;
    }
    return false;
}

/**
 * 镂空图像中的指定颜色
 * 警告:会改变$TopImg
 * @param resource $TopImg
 * @param resource $BottomImg
 * @param string|int|array $CleanColors 要去除的颜色值数组,为EdgeCheck或者检测边缘时表示自动检测边缘来确定
 * @param int $BottomX 上层图像相对于底层图像的X偏移
 * @param int $BottomY 上层图像相对于底层图像的Y偏移
 * @param int $alpha 叠加的透明度,暂未使用
 * @return bool|int 返回false或者替换像素的数量
 */
function hollowed_out_img($TopImg, $BottomImg, $CleanColors, $BottomX = 0, $BottomY = 0, $alpha = 0)
{
    if (empty($TopImg) || !is_resource($BottomImg) || empty($BottomImg) || !is_resource($BottomImg) || $CleanColors === NULL)
        return false;
    $top_w = ImageSX($TopImg);
    $top_h = ImageSY($TopImg);
    $bot_w = ImageSX($BottomImg);
    $bot_h = ImageSY($BottomImg);
    if ($bot_w < $top_w || $bot_h < $top_h) return false;
    $opt_ret = 0;

    /*
    if(is_string($CleanColor))
    {
        $CleanColor = colorname_to_rgb($CleanColor,1,$TopImg);
    }
    elseif(is_array($CleanColor) && count($CleanColor)>2)
    {
        if(function_exists('imagecolorallocatealpha'))
            $CleanColor = imagecolorallocatealpha($TopImg,(isset($CleanColor['R'])?$CleanColor['R']:$CleanColor[0]),(isset($CleanColor['G'])?$CleanColor['G']:$CleanColor[1]),(isset($CleanColor['B'])?$CleanColor['B']:$CleanColor[2]),(isset($CleanColor['A'])?$CleanColor['A']:$CleanColor[3]));
        $CleanColor =  imagecolorallocate($TopImg,(isset($CleanColor['R'])?$CleanColor['R']:$CleanColor[0]),(isset($CleanColor['G'])?$CleanColor['G']:$CleanColor[1]),(isset($CleanColor['B'])?$CleanColor['B']:$CleanColor[2]));
    }
    */
    $colors = array();
    if (is_string($CleanColors) || is_numeric($CleanColors))
        $colors[] = $CleanColors;
    else
        $colors = $CleanColors;
    $ti = 0;
    foreach ($colors as $CleanC) {
        if (is_string($CleanC)) {
            if ($CleanC == '检测边缘' || $CleanC == 'AutoCheck' || $CleanC == 'EdgeCheck') {
                $colors[$ti] = 'EdgeCheck';
            } else {
                $colors[$ti] = colorname_to_rgb($CleanC, 'index', $TopImg);
            }
        }
        $ti++;
    }

    $replaceTable = array();
    foreach ($colors as $CleanColor) {
        if ($CleanColor == 'EdgeCheck') {
            $xcp = null;
            if (empty($replaceTable)) {
                $rgb1 = imagecolorat($TopImg, 0, 0);
                $rgb2 = imagecolorat($TopImg, $top_w - 1, 0);
                $rgb3 = imagecolorat($TopImg, 0, $top_h - 1);
                $rgb4 = imagecolorat($TopImg, $top_w - 1, $top_h - 1);
                $rgb5 = imagecolorat($TopImg, $top_w / 2, 0);
                $rgb6 = imagecolorat($TopImg, $top_w / 2, $top_h - 1);
                $rgb7 = imagecolorat($TopImg, $top_w - 1, $top_h / 2);
                $rgb8 = imagecolorat($TopImg, 0, $top_h / 2);
                $xcp = array($rgb1, $rgb2, $rgb3, $rgb4, $rgb5, $rgb6, $rgb7, $rgb8);
            } else {
                $xcp = array();
                $rgb1 = $rgb2 = $rgb3 = $rgb4 = $rgb5 = $rgb6 = $rgb7 = $rgb8 = false;
                for ($j = 0, $i = 0; $j < $top_h && $i < $top_w; $j++, $i++) {
                    if ($replaceTable[$j][$i] != 0) continue;
                    $rgb1 = imagecolorat($TopImg, $i, $j);
                    $xcp[] = $rgb1;
                    break;
                }
                for ($j = 0, $i = $top_w - 1; $j < $top_h && $i > 0; $j++, $i--) {
                    if ($replaceTable[$j][$i] != 0) continue;
                    $rgb2 = imagecolorat($TopImg, $i, $j);
                    $xcp[] = $rgb2;
                    break;
                }
                for ($j = $top_h - 1, $i = 0; $j > 0 && $i < $top_w; $j--, $i++) {
                    if ($replaceTable[$j][$i] != 0) continue;
                    $rgb3 = imagecolorat($TopImg, $i, $j);
                    $xcp[] = $rgb3;
                    break;
                }
                for ($j = $top_h - 1, $i = $top_w - 1; $j < $top_h && $i < $top_w; $j--, $i--) {
                    if ($replaceTable[$j][$i] != 0) continue;
                    $rgb4 = imagecolorat($TopImg, $i, $j);
                    $xcp[] = $rgb4;
                    break;
                }
                for ($j = 0, $i = $top_w / 2; $j < $top_h; $j++) {
                    if ($replaceTable[$j][$i] != 0) continue;
                    $rgb5 = imagecolorat($TopImg, $i, $j);
                    $xcp[] = $rgb5;
                    break;
                }
                for ($j = $top_h - 1, $i = $top_w / 2; $j > 0; $j--) {
                    if ($replaceTable[$j][$i] != 0) continue;
                    $rgb6 = imagecolorat($TopImg, $i, $j);
                    $xcp[] = $rgb6;
                    break;
                }
                for ($j = $top_h / 2, $i = $top_w - 1; $i > 0; $i--) {
                    if ($replaceTable[$j][$i] != 0) continue;
                    $rgb7 = imagecolorat($TopImg, $i, $j);
                    $xcp[] = $rgb7;
                    break;
                }
                for ($j = $top_h / 2, $i = 0; $i < $top_w; $i++) {
                    if ($replaceTable[$j][$i] != 0) continue;
                    $rgb8 = imagecolorat($TopImg, $i, $j);
                    $xcp[] = $rgb8;
                    break;
                }
            }
            $maxCv = 0;
            $maxCi = null;
            foreach ($xcp as $ite) {
                if ($maxCi === $ite) continue;
                $xcount = count(array_keys($xcp, $ite, true));
                if ($xcount > $maxCv) {
                    $maxCv = $xcount;
                    $maxCi = $ite;
                }
            }
            if ($maxCv > 3) $CleanColor = $maxCi;
        }
        for ($j = 0; $j <= $top_h - 1; $j++) {
            for ($i = 0; $i <= $top_w - 1; $i++) {
                if (!isset($replaceTable[$j][$i]))
                    $replaceTable[$j][$i] = 0;
                $rgb = imagecolorat($TopImg, $i, $j);
                if ($rgb != $CleanColor)
                    continue;
                else {
                    if (($i + $BottomX >= $bot_w) || ($j + $BottomY >= $bot_h))
                        continue;
                    $rgb2 = imagecolorat($BottomImg, $i + $BottomX, $j + $BottomY);
                    $r2 = ($rgb2 >> 16) & 0xFF;
                    $g2 = ($rgb2 >> 8) & 0xFF;
                    $b2 = $rgb2 & 0xFF;
                    $a2 = ($rgb2 & 0x7F000000) >> 24;
                    if (function_exists('imagecolorallocatealpha')) $color = imagecolorallocatealpha($TopImg, $r2, $g2, $b2, $a2); else
                        $color = imagecolorallocate($TopImg, $r2, $g2, $b2);
                    $replaceTable[$j][$i] = 1;
                    if (imagesetpixel($TopImg, $i, $j, $color)) $opt_ret++;
                }
            }
        }
    }
    unset($replaceTable);
    return $opt_ret;
}


/**
 * 生成缩放图或者水印图片
 * @param array $argArr 参数设置,需要指定:ImgSrc,ProcessType,WatermarkOutputPath,ThumbnailOutputPath,包括以下项:
 *        String $argArr['ImgSrc'] 源图片路径
 *        int $argArr['ProcessType'] 处理类型位标识(0位为文字水印,1位为图片水印,2位为生成缩放图)
 *        int $argArr['WatermarkOutputQuality'] 水印生成图片的质量，数字越大越清晰，文件尺寸越大(default:100)
 *        String $argArr['WatermarkOutputPath'] 生成加水印图片保存文件夹路径(包括文件名)
 *        String $argArr['OriginalImgBakPath'] 要将源图片备份到的路径(default:APP_PATH.'upload/origimgs/'),警告:必须将此目录设置为不可读
 *        String $argArr['DelOriImgAfterMark'] 水印操作后是否删除原图,默认为true
 *        String $argArr['MarkText'] 水印字符串(default:网站名)
 *        int $argArr['MarkTextPosition'] 水印字符的绘制位置,九宫格位置代号,左上1,上中2,右上3,中左4...右下9,0为随机位置
 *        int $argArr['MarkTextTransparency'] 文字水印透明度0-100，数字小透明高(default:85)
 *        String $argArr['MarkTextColor'] 水印字符的颜色,如果支持可以带Alpha,即[A] 默认为'orange',random为随机
 *        String $argArr['MarkTextFont'] 水印文字的字体路径,可以是random,也可以使用`{fonts dir}|random`,表示在view/font或者指定的目录下随机选取
 *        float $argArr['MarkTextSize'] 水印字符串字体大小, 默认为12,以像素为单位,8磅约为12像素,9磅约为14像素,18磅约为25像素
 *        int $argArr['MarkTextAngle'] 水印字符串的旋转角度,一般以左下角为原点,-1为随机角度;(default:0)
 *        String $argArr['MarkImg'] 水印图片路径(default:APP_PATH.'view/img/water-small.png')
 *        String $argArr['ThumbnailOutputPath'] 缩放图保存文件夹路径(包括文件名)
 *        int $argArr['MarkImgPosition'] 水印图片的绘制位置,九宫格位置代号,左上1,上中2,右上3,中左4...右下9,0为随机位置
 *        int $argArr['MarkImgMergedAccording'] 图片水印透明度0-100，数字小透明高(default:80)
 *        int $argArr['MarkImgAngle'] 水印图片的旋转角度,一般以左下角为原点,-1为随机角度;(default:0)
 *        string|int $argArr['MarkImgCleanColor'] 水印图片中需要清除的一种颜色,默认为R127G0B127
 *        int $argArr['ThumbnailOutputQuality'] 缩放图清晰度0-100，数字越大越清晰，文件尺寸越大(default:75)
 *        int $argArr['ThumbnailHeight'] 定义缩放图高度，为0时根据$argArr['ThumbnailWidth']高度等比例缩放(default:150)
 *        int $argArr['ThumbnailWidth'] 定义缩放图宽度，为0时根据$argArr['ThumbnailHeight']高度等比例缩放(default:0)
 *        int $argArr['ThumbnailImgType'] 缩放图的保存类型,默认为IMAGETYPE_UNKNOWN,如果ThumbnailOutputPath中没有指定扩展名,也由此决定
 *        int $argArr['MaxFileSize'] 源文件大小限制,单位BYTE.0为无限制(default:8M)
 * @param string|null  $img_src 原图片路径,如果有,则会覆盖$argArr配置ImgSrc
 * @param string|null  $save_path 保存图片路径,如果有,则会覆盖$argArr配置WatermarkOutputPath|ThumbnailOutputPath
 * @return int|array 返回错误值或者可能已经改变值的设置参数:-1:gd2库没有开启;-2:源文件不存在;-3:源图片为空或者太大;-4不支持源图片的格式;-5:源图片打开错误;-6:水印图片格式错误或者无法打开;-7没有指定保存路径;-8保存图片发生错误;-9缩放图设置错误;-10水印图片大于源图片;-11:其它参数错误
 */
function image_process(array $argArr,string $img_src=null,string $save_path=null)
{
    global $conf;
    $tmpret = false;
    $tmpstr = null;
    $saved_path = null;
    if(empty($img_src)) $img_src = $argArr['ImgSrc'];
    if (!extension_loaded('gd')) return -1;
    if (empty($argArr) || empty($img_src) || empty($argArr['ProcessType'])) return -2;
    $OutputPath = $save_path;
    if(empty($OutputPath)){
        $OutputPath = (empty($argArr['WatermarkOutputPath'])?$argArr['ThumbnailOutputPath']:$argArr['WatermarkOutputPath']);
    }
    if ((($argArr['ProcessType'] & 3) != 0 && empty($OutputPath)) || (($argArr['ProcessType'] & 4) != 0 && empty($argArr['ThumbnailOutputPath']) && empty($OutputPath)))
        return -7;
    /**
     * 默认参数
     * 不包含ImgSrc,ProcessType,MarkText,WatermarkOutputPath,ThumbnailOutputPath
     */
    static $DefaultArgs = array(
        'WatermarkOutputQuality' => 90,
        'OriginalImgBakPath' => APP_PATH . 'upload' . DIRECTORY_SEPARATOR . 'origimgs' . DIRECTORY_SEPARATOR,
        'DelOriImgAfterMark' => true,
        'MarkTextPosition' => 1,
        'MarkTextTransparency' => 85,
        'MarkTextColor' => 'orange',
        'MarkTextFont' => APP_PATH . 'view' . DIRECTORY_SEPARATOR . 'font' . DIRECTORY_SEPARATOR . 'fontawesome-webfont.ttf',
        'MarkTextSize' => 12,
        'MarkTextAngle' => 0,
        'MarkImg' => null,
        'MarkImgPosition' => 1,
        'MarkImgMergedAccording' => 80,
        'MarkImgAngle' => 0,
        'MarkImgCleanColor' => null,
        'ThumbnailOutputQuality' => 100,
        'ThumbnailHeight' => 150,
        'ThumbnailWidth' => 0,
        'ThumbnailImgType' => IMAGETYPE_UNKNOWN,
        'MaxFileSize' => 8290304,
        'RandomFontsExclude' => []
    );
    if (empty($DefaultArgs['MarkText'])) $DefaultArgs['MarkText'] = $conf['sitename'];
    if (empty($DefaultArgs['MarkImg'])) {
        if (!empty($conf['logo_water_url']))
            $DefaultArgs['MarkImg'] = $conf['logo_water_url'];
        else
            $DefaultArgs['MarkImg'] = APP_PATH . 'view/img/water-small.png';
    }
    $argArr = array_merge($DefaultArgs, $argArr);
    if (($argArr['ProcessType'] & 4) != 0 && ($argArr['ThumbnailWidth'] + $argArr['ThumbnailHeight'] < 2))
        return -9;

    //随机字体处理
    $random_with_dir = false;
    if (empty($argArr['MarkTextFont']) || $argArr['MarkTextFont'] == 'random' || ($random_with_dir = str_ends_with($argArr['MarkTextFont'],'|random'))) {
        $fontfs = cache_get('font_files');
        if (empty($fontfs)) {
            $font_dir = APP_PATH . 'view' . DIRECTORY_SEPARATOR . 'font';
            if($random_with_dir){
                $font_dir = substr($argArr['MarkTextFont'],0,-5);
            }
            $fontfs = get_filenames($font_dir, true);
            if (!empty($fontfs)) {
                $tmpFonts = array();
                if (!empty($argArr['RandomFontsExclude'])) {//排除掉不需要的字体
                    foreach ($fontfs as &$searchFontV) {
                        $isExclued = false;
                        foreach ($argArr['RandomFontsExclude'] as &$f_name2) {
                            $fnLen = strlen($f_name2) * -1;
                            if (stripos(substr($searchFontV, $fnLen), $f_name2) === 0) {
                                $isExclued = true;
                                break;
                            }
                        }
                        if (!$isExclued)
                            $tmpFonts[] = &$searchFontV;
                    }
                    if (count($tmpFonts) != count($fontfs)) {
                        $fontfs = &$tmpFonts;
                    }
                    unset($tmpFonts);
                }
                cache_set('font_files', $fontfs, 24 * 3600 * 3);//缓存三天
            }
        }
        if (!empty($fontfs)) {
            $ffs = count($fontfs);
            if ($ffs == 1) $argArr['MarkTextFont'] = $fontfs[0];
            else
                $argArr['MarkTextFont'] = $fontfs[mt_rand(0, $ffs - 1)];
        }
        unset($fontfs);
    }
    $optTag = 0;



    if (!is_file($img_src)) return -2;
    $tmpret = filesize($img_src);
    if (!$tmpret || $tmpret > $argArr['MaxFileSize']) return -3;
    $src_type = get_img_type($img_src);//判断源图片文件类型
    if ($src_type == IMAGETYPE_UNKNOWN) return -4;
    $src_im = get_img_resource($img_src, $src_type);
    if (empty($src_im)) return -5;
    $src_w = doubleval(ImageSX($src_im)); //获得图片宽
    $src_h = doubleval(ImageSY($src_im)); //获得图片高

    //保存原图片文件
    $OriginalImgBakFile = null;
    if (($argArr['ProcessType'] & 3) != 0 && !empty($argArr['OriginalImgBakPath'])) {
        $OriginalImgBakFile = $argArr['OriginalImgBakPath'];
        $bk_3 = pathinfo($OriginalImgBakFile);
        if(!isset($bk_3['extension'])){
            $lastchr = $argArr['OriginalImgBakPath'][strlen($argArr['OriginalImgBakPath']) - 1];
            if ($lastchr != '/' && $lastchr != '\\'){
                $argArr['OriginalImgBakPath'] .= DIRECTORY_SEPARATOR;
            }
            $OriginalImgBakFile .= basename($img_src);
            $bk_3 = pathinfo($OriginalImgBakFile);
        }
        if(!is_dir($bk_3['dirname'])){
            $bk_p2 = dirname($bk_3['dirname']);
            xn_mkdir($bk_p2,0777,true);
            mkdir($bk_3['dirname'],0200);//目录只可写
        }
        if($img_src == $OriginalImgBakFile || !copy($img_src, $OriginalImgBakFile)){
            $OriginalImgBakFile = null;
        }
    }

    if (($argArr['ProcessType'] & 7) > 0) {
        $dst_im = imagecreatetruecolor($src_w, $src_h);//根据原图尺寸创建一个相同大小的真彩色位图
        $white = imagecolorallocate($dst_im, 255, 255, 255);//白
        //给新图填充背景色
        $black = imagecolorallocate($dst_im, 0, 0, 0);//黑
        $red = imagecolorallocate($dst_im, 255, 0, 0);//红
        $colRGB = colorname_to_rgb($argArr['MarkTextColor']);
        $select_color = imagecolorallocate($dst_im, $colRGB['R'], $colRGB['G'], $colRGB['B']);//橙
        if (function_exists('imagecolorallocatealpha')) {
            $alpha = imagecolorallocatealpha($dst_im, 0, 0, 0, 127);//透明颜色
            $select_color = imagecolorallocatealpha($dst_im, $colRGB['R'], $colRGB['G'], $colRGB['B'], $colRGB['A']);
        }
        if ($alpha && ($src_type == IMAGETYPE_GIF || $src_type == IMAGETYPE_PNG || $src_type == IMAGETYPE_WEBP))
            $tmpret = imagefill($dst_im, 0, 0, $alpha);//透明背景
        else  $tmpret = imagefill($dst_im, 0, 0, $white);
        if ($tmpret) $tmpret = imagecopymerge($dst_im, $src_im, 0, 0, 0, 0, $src_w, $src_h, 100);//原图图像写入新建真彩位图中
        if (!$tmpret) {
            imagedestroy($src_im);
            imagedestroy($dst_im);
            return -5;
        }
        //imagefilledrectangle($dst_im,1,$src_h-15,80,$src_h,$white);
        if (($argArr['ProcessType'] & 1) != 0)//加水印字符串
        {
            $fs_pt = point_pixel(2, $argArr['MarkTextSize']);//转换为磅
            if ($argArr['MarkTextAngle'] == -1)//随机旋转角度:
                $argArr['MarkTextAngle'] = mt_rand(0, 359);
            $textbox = imagettfbbox($fs_pt, $argArr['MarkTextAngle'], $argArr['MarkTextFont'], $argArr['MarkText']);
            if (!empty($textbox)) {
                $tf2 = rect_for_box($textbox);
                $tf_w = $tf2['W'];
                $tf_h = $tf2['H'];
                $drawXY = get_draw_position($argArr['MarkTextPosition'], $src_w, $src_h, $tf_w, $tf_h, $tf2['L'], $tf2['T']);
                if (!empty($drawXY)) {
                    $txt_encode = mb_detect_encoding($argArr['MarkText']);
                    if ($txt_encode != 'UTF-8')
                        $argArr['MarkText'] = mb_convert_encoding($argArr['MarkText'], 'UTF-8', $txt_encode);
                    $tmpret = imagettftext($dst_im, $argArr['MarkTextSize'], $argArr['MarkTextAngle'], $drawXY['X'], $drawXY['Y'], $select_color, $argArr['MarkTextFont'], $argArr['MarkText']);
                    if ($tmpret) $optTag |= 1;
                }
            }
        }
        if (($argArr['ProcessType'] & 2) != 0)//加图片水印
        {
            if (file_exists($argArr['MarkImg'])) {
                $mi_type = get_img_type($argArr['MarkImg']);//判断源图片文件类型
                if ($mi_type != IMAGETYPE_UNKNOWN)
                    $res_im = get_img_resource($argArr['MarkImg'], $mi_type);
            }
            if (empty($res_im)) {
                imagedestroy($src_im);
                imagedestroy($dst_im);
                return -6;
            }
            $rotated_img = false;
            $cleanColorV = null;
            if (empty($argArr['MarkImgCleanColor']))
                $argArr['MarkImgCleanColor'] = 'Purple';
            $cleanColorV = colorname_to_rgb($argArr['MarkImgCleanColor']);
            $bgd_color = imagecolorallocate($res_im, 127, 0, 127);
            if ($cleanColorV !== false)
                $bgd_color = imagecolorallocate($res_im, $cleanColorV['R'], $cleanColorV['G'], $cleanColorV['B']);
            //if (function_exists('imagecolorallocatealpha')) $bgd_color = imagecolorallocatealpha($res_im, $cleanColorV['R'], $cleanColorV['G'], $cleanColorV['B'],$cleanColorV['A']);

            if ($argArr['MarkImgAngle'] == -1)//水印图片随机旋转角度:
                $argArr['MarkImgAngle'] = mt_rand(0, 359);
            if ($argArr['MarkImgAngle'] != 0)//旋转水印图片
            {
                //imagesavealpha($res_im, true);
                $rotate_img = imagerotate($res_im, $argArr['MarkImgAngle'], $bgd_color);

                if (!empty($rotate_img) && is_resource($rotate_img)) {
                    imagedestroy($res_im);
                    $res_im = $rotate_img;
                    $rotated_img = true;
                }
            }
            if (!empty($res_im) && is_resource($res_im)) {

                //imagesavealpha($res_im, true);
                $im_w = doubleval(ImageSX($res_im)); //获得旋转后的水印图片宽
                $im_h = doubleval(ImageSY($res_im)); //获得旋转后的水印图片高
                if ($src_w <= $im_w || $src_h <= $im_h || $im_w < 5 || $im_h < 2)//水印图片大于源图片
                {
                    imagedestroy($res_im);
                    imagedestroy($src_im);
                    imagedestroy($dst_im);
                    return -10;
                }
                $drawXY = get_draw_position($argArr['MarkImgPosition'], $src_w, $src_h, $im_w, $im_h);
                if (!empty($drawXY)) {

                    //$tmpret = hollowed_out_img($res_im, $dst_im, $cleanColors, $drawXY['X'], $drawXY['Y']);
                    //设定图像的混色模式
                    $bgd_color = imagecolorallocate($res_im, 127, 0, 127);
                    if ($cleanColorV !== false)
                        $bgd_color = imagecolorallocate($res_im, $cleanColorV['R'], $cleanColorV['G'], $cleanColorV['B']);
                    $transparent_color = imagecolortransparent($res_im, $bgd_color);//把背景色设置为透明
                    $tmpret = imagefill($res_im, 0, 0, $transparent_color);
                    $tmpret = imagealphablending($res_im, true);
                    //$tmpret = imagecopymerge($dst_im, $res_im, $drawXY['X'], $drawXY['Y'], 0, 0, $im_w, $im_h, $argArr['MarkImgMergedAccording']);// 合并两个图像，设置水印透明度$waterclearly
                    $tmpret = imagecopy($dst_im, $res_im, $drawXY['X'], $drawXY['Y'], 0, 0, $im_w, $im_h);
                    if ($tmpret) $optTag |= 2;
                }
            }
            if (!empty($res_im)) imagedestroy($res_im);
        }
        if ($optTag != 0) {//已经成功进行水印操作:
            $saved_path = save_img_resource($dst_im, $OutputPath, $src_type, $argArr['WatermarkOutputQuality'], false);
            if (!empty($saved_path) && is_string($saved_path)) {
                if($OutputPath != $saved_path) $OutputPath = $argArr['WatermarkOutputPath'] = $saved_path;
            }
            elseif(!empty($OriginalImgBakFile)){//执行失败,删除备份
                @xn_unlink($OriginalImgBakFile);
            }
        }

        if (($argArr['ProcessType'] & 4) != 0)//图片缩放
        {
            //补充ThumbnailOutputPath与ThumbnailImgType
            if(empty($argArr['ThumbnailOutputPath'])) $argArr['ThumbnailOutputPath'] = $OutputPath;
            else $OutputPath = $argArr['ThumbnailOutputPath'];
            $sf_ext = pathinfo($OutputPath, PATHINFO_EXTENSION);
            if (empty($sf_ext)) {
                if ($argArr['ThumbnailImgType'] == IMAGETYPE_UNKNOWN)
                    $argArr['ThumbnailImgType'] = IMAGETYPE_JPEG;
                $sf_ext = image_type_to_extension($argArr['ThumbnailImgType'], false);
                $OutputPath .= '.' . $sf_ext;
            } else {
                if ($argArr['ThumbnailImgType'] == IMAGETYPE_UNKNOWN) {
                    $argArr['ThumbnailImgType'] = extension_to_image_type($sf_ext);
                    if ($argArr['ThumbnailImgType'] == IMAGETYPE_UNKNOWN) {
                        $argArr['ThumbnailImgType'] = IMAGETYPE_JPEG;
                        $OutputPath .= '.jpg';
                    }
                }
            }

            //计算等比缩放的缺省值
            if ($argArr['ThumbnailWidth'] == 0) $argArr['ThumbnailWidth'] = intval($argArr['ThumbnailHeight'] * ($src_w / $src_h));
            if ($argArr['ThumbnailHeight'] == 0) $argArr['ThumbnailHeight'] = intval($argArr['ThumbnailWidth'] * ($src_h / $src_w));
            if ($src_w != $argArr['ThumbnailWidth'] || $src_h != $argArr['ThumbnailHeight']) {
                $dst_image = ImageCreateTrueColor($argArr['ThumbnailWidth'], $argArr['ThumbnailHeight']);
                if (function_exists('imagecopyresampled')) {
                    $tmpret = imagecopyresampled($dst_image, $dst_im, 0, 0, 0, 0, $argArr['ThumbnailWidth'], $argArr['ThumbnailHeight'], $src_w, $src_h);
                } else {
                    $tmpret = ImageCopyResized($dst_image, $dst_im, 0, 0, 0, 0, $argArr['ThumbnailWidth'], $argArr['ThumbnailHeight'], $src_w, $src_h);
                }

                if ($tmpret) {
                    $saved_path = save_img_resource($dst_image, $OutputPath, $argArr['ThumbnailImgType'], $argArr['ThumbnailOutputQuality']);
                    if (!empty($saved_path) && is_string($saved_path)) {
                        $optTag |= 5;
                        if ($OutputPath != $saved_path){
                            $OutputPath = $argArr['ThumbnailOutputPath'] = $saved_path;
                        }
                    }
                    imagedestroy($dst_im);//其后可能还有操作,替换资源句柄
                    $dst_im = $dst_image;
                } else {
                    if ($dst_image) imagedestroy($dst_image);
                }
            }
        }
//todo:---------------------继续处理其它操作----------------------
//  ...............
//  ...............
//---------------------------------------------------------

        if (!is_string($saved_path)) {
            if (!empty($dst_im) && is_resource($dst_im)) imagedestroy($dst_im);
            return -8;
        }
        //删除源文件
        if (($optTag & 3) != 0 && $argArr['DelOriImgAfterMark'] && $img_src != $OutputPath) {
            @unlink($img_src);
        }
        return $argArr;
    }
    return -11;

}



?>